#!/bin/bash

# 服务器环境配置脚本
# 在服务器 82.157.51.127 上执行此脚本来配置 CI/CD 环境

set -e

# 配置变量
SERVER_IP="82.157.51.127"
PROJECT_NAME="tetris-game"
PROJECT_DIR="/opt/jpom/projects/${PROJECT_NAME}"
WEBHOOK_PORT="9999"
APP_PORT="3000"

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

log "🚀 开始配置服务器环境..."

# 1. 更新系统
log "📦 更新系统包..."
yum update -y

# 2. 安装 EPEL 仓库
log "📦 安装 EPEL 仓库..."
yum install -y epel-release

# 3. 安装必要的软件
log "🔧 安装必要软件..."
yum install -y \
    curl \
    wget \
    git \
    python3 \
    python3-pip \
    docker \
    docker-compose \
    nginx \
    firewalld \
    net-tools

# 4. 启动 Docker 服务
log "🐳 配置 Docker..."
systemctl start docker
systemctl enable docker
usermod -aG docker $USER

# 5. 安装 Python 依赖
log "🐍 安装 Python 依赖..."
pip3 install flask

# 6. 创建项目目录
log "📁 创建项目目录..."
mkdir -p "${PROJECT_DIR}"
mkdir -p /var/log

# 7. 配置防火墙 (firewalld)
log "🔥 配置防火墙..."
systemctl start firewalld
systemctl enable firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-port=${WEBHOOK_PORT}/tcp
firewall-cmd --permanent --add-port=${APP_PORT}/tcp
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

# 8. 启动 Nginx 服务
log "🌐 启动 Nginx..."
systemctl start nginx
systemctl enable nginx

# 9. 配置 Nginx 反向代理
log "🌐 配置 Nginx..."
cat > /etc/nginx/sites-available/tetris-webhook << EOF
server {
    listen 80;
    server_name ${SERVER_IP};
    
    # Webhook 接收器
    location /webhook/ {
        proxy_pass http://127.0.0.1:${WEBHOOK_PORT};
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
    
    # 游戏应用
    location / {
        proxy_pass http://127.0.0.1:${APP_PORT};
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
    
    # 健康检查
    location /health {
        proxy_pass http://127.0.0.1:${WEBHOOK_PORT}/health;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
    }
}
EOF

# 启用站点 (CentOS/RHEL 使用不同的配置方式)
# 备份原配置
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup

# 在主配置文件中包含我们的配置
if ! grep -q "include /etc/nginx/conf.d/tetris-webhook.conf" /etc/nginx/nginx.conf; then
    sed -i '/include \/etc\/nginx\/conf.d\/\*.conf;/a\    include /etc/nginx/conf.d/tetris-webhook.conf;' /etc/nginx/nginx.conf
fi

# 移动配置文件到正确位置
mv /etc/nginx/sites-available/tetris-webhook /etc/nginx/conf.d/tetris-webhook.conf

nginx -t && systemctl reload nginx

# 10. 创建 Webhook 接收器服务
log "⚙️ 配置 Webhook 服务..."
# 服务文件将通过 Git 仓库获取

# 11. 设置 SELinux (如果启用)
log "🔒 配置 SELinux..."
if command -v getenforce >/dev/null 2>&1; then
    if [ "$(getenforce)" = "Enforcing" ]; then
        log "检测到 SELinux，配置相关策略..."
        setsebool -P httpd_can_network_connect 1
        setsebool -P httpd_can_network_relay 1
    fi
fi

# 12. 显示配置信息
log "✅ 服务器配置完成！"
echo ""
echo "📋 配置信息:"
echo "  服务器IP: ${SERVER_IP}"
echo "  项目目录: ${PROJECT_DIR}"
echo "  Webhook端口: ${WEBHOOK_PORT}"
echo "  应用端口: ${APP_PORT}"
echo "  Webhook URL: http://${SERVER_IP}/webhook/gitee"
echo "  应用访问: http://${SERVER_IP}"
echo "  健康检查: http://${SERVER_IP}/health"
echo ""
echo "🔧 下一步操作:"
echo "1. 将项目代码推送到 Gitee"
echo "2. 在 Gitee 仓库中配置 Webhook: http://${SERVER_IP}/webhook/gitee"
echo "3. 手动执行一次构建测试: ${PROJECT_DIR}/jpom-build.sh"
echo "4. 启动 Webhook 服务: systemctl start webhook-receiver"
echo ""
echo "🎉 环境配置完成！"
